<?php

namespace app\admin\service;

use app\common\BaseHelper as Helper;
use app\admin\model\Meeting as MeetingMdl;

use think\Db;
use think\Exception;

class Meeting
{

    /**
     * 生成会议签到二维码
     *
     * @return bool|string
     */
    public static function createMeetingCode($meetingId, $townId){
        $businessId = db('townprogram')->where(['townId' => $townId])->value('id');
        // 接口调用凭据
        $access_token = json_decode(Helper::curlGet(config('miniprogram.wx_domain').'/api/WechatOpenApi/getAuthorizerToken?b=' . $businessId . '&isRefresh=true'),true);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
        $postData["scene"] = $meetingId;
        $postData["path"] = "pages/home/Home";
        //$postData["page"] = "pages/home/Home";

        $result = Helper::curlPost($url, json_encode($postData));
        if(json_decode($result,true)['errcode']){
            return false;
        }
        $upload = config('path.Upload_path');
        $savepath = 'meeting/' . date('Ymd');
        $filepath = $upload . $savepath;
        if(!file_exists($filepath)){
            mkdir($filepath, 0777, true);
        }
        $filename = Helper::getUUID() . '.png';

        file_put_contents($filepath . '/' . $filename, $result);

        return $savepath . '/' . $filename;
    }

    /**
     * 发送短信
     */
    public static function sendSms($meetingId, $content){
        $smsObj = new \app\lib\Sms();

        try {
            // 参会人员
            $model = model('Joinmeeting');

            $where = [
                'meetingId' => $meetingId
            ];
            $join = [
                ['__MEETING__ b', 'b.id = a.meetingId'],
                ['__MEMBER__ m', 'm.id = a.memberId']
            ];
            $field = 'b.title, b.address, b.startTime, m.mobile';
            $joinList = $model->alias('a')->where($where)->join($join)->field($field)->select();
            if ($joinList) {
                foreach ($joinList as $data){
                    $data = json_decode($data,true);
                    $message = '';
                    $message .= "会议提醒：\n会议主题：" . $data['title'] . "\n";
                    $message .= '会议开始时间：' . date('Y-m-d H:i', $data['startTime']) . "\n";
                    $message .= '会议地点：' . $data['address']. "\n";
                    $message .= $content . ' 【智慧乡镇】';

                    $smsRes = $smsObj->sendMess($data['mobile'], $message);
                    if (isset($smsRes)) {
                        if ($smsRes['msg'] == 'ok') {
                            trace($data['mobile'] . ': 发送会议短信成功','log');
                        } else {
                            trace($data['mobile'] . ': 发送会议短信失败','notice');
                        }
                    }
                }
            }
        } catch (Exception $e) {
            trace($e->getMessage(),'error');
            return false;
        }

        return true;
    }
}